package com.fuhailiu.opengl.renders;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.view.MotionEvent;

import com.fuhailiu.opengl.utils.ArrayUtil;
import com.fuhailiu.opengl.utils.LogUtil;
import com.fuhailiu.opengl.view.GLViewGroup;
import com.fuhailiu.opengl.widget.GLPolygonOffset;

public class RenderPolygonOffset extends AbsRender {

	private final String TAG = getClass().getSimpleName();

	private GLPolygonOffset mGLPolygonOffset;

	private float mRatio;

	public RenderPolygonOffset(Context context) {
		super(context);
	}

	@Override
	public void onSurfaceChanged(GL10 gl, int width, int height) {
		super.onSurfaceChanged(gl, width, height);
		mRatio = 1.0f * mSurfaceWidth / mSurfaceHeight;
	}

	@Override
	protected GLViewGroup makeWorld(Context context) {
		LogUtil.LogD(TAG, "makeWorld   <---");

		GLViewGroup layout = new GLViewGroup(context);

		mGLPolygonOffset = new GLPolygonOffset(context, 0.15f, 36);
		layout.addView(mGLPolygonOffset);

		LogUtil.LogD(TAG, "makeWorld   --->");

		return layout;
	}

	private final String[] menuArray = new String[] { "关闭多边形偏移", "打开多边形偏移" };
	private final int[] menuFunc = new int[] { GLPolygonOffset.OFFSET_OFF, GLPolygonOffset.OFFSET_ON };

	@Override
	public String[] getMenuInfo() {
		return menuArray;
	}

	@Override
	public void onMenuSelected(String title) {
		int index = ArrayUtil.getIndex(menuArray, title);
		if (index != -1) {
			int mode = menuFunc[index];
			mGLPolygonOffset.setOffsetMode(mode);
		}
	}

	// 最后一次触摸点坐标
	private float mLastTouchX;
	private float mLastTouchY;

	@Override
	public void onTouchEvent(MotionEvent event) {
		float x = event.getX();
		float y = event.getY();

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			break;

		case MotionEvent.ACTION_MOVE:
			float deltaX = x - mLastTouchX;
			float deltaY = y - mLastTouchY;
			mGLPolygonOffset.mTranslateX += deltaX / mSurfaceWidth * 2 * mRatio;
			mGLPolygonOffset.mTranslateY += -deltaY / mSurfaceHeight * 2;
			break;

		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			break;
		}

		mLastTouchX = x;
		mLastTouchY = y;
	}

}
